using Microsoft.AspNetCore.Mvc;
using NLog;
using SqlSugar;
using WYD.Common;
using WYD.Infrastructure.Attribute;
using WYD.Infrastructure.Controllers;
using WYD.Infrastructure.Enums;
using WYD.Infrastructure.ExceptionImpl;
using WYD.Infrastructure.Model;
using WYD.ServiceCore.Filters;
using WYD.ServiceCore.Model;
using WYD.ServiceCore.Model.Dto;
using WYD.ServiceCore.Services.IService;

namespace WYD.Admin.WebApi.Controllers.System
{
    /// <summary>
    /// 文件存储Controller
    /// </summary>
    [Verify]
    [Route("tool/file")]
    [ApiExplorerSettings(GroupName = "sys")]
    public class SysFileController : BaseController
    {
        /// <summary>
        /// 文件存储接口
        /// </summary>
        private readonly ISysFileService _sysFileService;

        public SysFileController(ISysFileService sysFileService)
        {
            _sysFileService = sysFileService;
        }
        
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 查询文件存储列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("list")]
        [ActionPermissionFilter(Permission = "tool:file:list")]
        public IActionResult QuerySysFile([FromQuery] SysFileQueryDto parm)
        {
            var predicate = Expressionable.Create<SysFile>();

            predicate = predicate.AndIF(parm.BeginCreate_time != null, it => it.Create_time >= parm.BeginCreate_time);
            predicate = predicate.AndIF(parm.EndCreate_time != null, it => it.Create_time <= parm.EndCreate_time);
            predicate = predicate.AndIF(parm.StoreType != null, m => m.StoreType == parm.StoreType);
            predicate = predicate.AndIF(parm.FileId != null, m => m.Id == parm.FileId);

            var response = _sysFileService.GetPages(predicate.ToExpression(), parm, x => x.Id, OrderByType.Desc);
            return SUCCESS(response);
        }

        /// <summary>
        /// 查询文件存储详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("{Id}")]
        [ActionPermissionFilter(Permission = "tool:file:query")]
        public IActionResult GetSysFile(long Id)
        {
            var response = _sysFileService.GetFirst(x => x.Id == Id);

            return SUCCESS(response);
        }

        //TODO
        /// <summary>
        /// 删除文件存储
        /// </summary>
        /// <returns></returns>
        // [HttpDelete("{ids}")]
        // [ActionPermissionFilter(Permission = "tool:file:delete")]
        // [Log(Title = "文件存储", BusinessType = BusinessType.DELETE)]
        // public async Task<IActionResult> DeleteSysFile(string ids)
        // {
        //     long[] idsArr = Tools.SpitLongArrary(ids);
        //     if (idsArr.Length <= 0) { return ToResponse(ApiResult.Error($"删除失败Id 不能为空")); }
        //
        //     var response = await _sysFileService.DeleteSysFileAsync(idsArr);
        //
        //     return ToResponse(response);
        // }

        /// <summary>
        /// 文件存储导出
        /// </summary>
        /// <returns></returns>
        [Log(BusinessType = BusinessType.EXPORT, IsSaveResponseData = false, Title = "文件存储")]
        [HttpGet("export")]
        [ActionPermissionFilter(Permission = "tool:file:export")]
        public IActionResult Export()
        {
            var list = _sysFileService.GetAll();

            string sFileName = ExportExcel(list, "SysFile", "文件存储");
            return SUCCESS(new { path = "/export/" + sFileName, fileName = sFileName });
        }
        
        //TODO
        /// <summary>
        /// 通过文件ID下载文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        // [HttpPost("download")]
        // public IActionResult Download([FromBody] SysFile file)
        // {
        //     var sysFile = _sysFileService.Queryable().Where(it => it.Id == file.Id).First();
        //     if (sysFile == null)
        //     {
        //         return NoContent();
        //     }
        //
        //     Stream? stream = null;
        //     switch ((StoreType)Enum.Parse(typeof(StoreType), sysFile.StoreType.ToString() ?? string.Empty))
        //     {
        //         //TODO
        //         case StoreType.LOCAL:
        //             stream = sysFile.IsEncrypted == "1" ? _sysFileService.DecryptSysFileStream(sysFile.FileUrl) 
        //                 : new FileStream(sysFile.FileUrl, FileMode.Open);
        //             break;
        //         case StoreType.ALIYUN:
        //             stream = AliyunOssHelper.DownloadFile(sysFile.FileUrl, "", sysFile.IsEncrypted == "1");
        //             break;
        //         default:
        //             throw new CustomException("不支持的存储类型");
        //     }
        //     if (stream != null)
        //     {
        //         return new FileStreamResult(stream, "application/octet-stream")
        //         {
        //             FileDownloadName = sysFile.RealName
        //         };
        //     }
        //     else
        //     {
        //         return NoContent();
        //     }
        // }
        
        //TODO
        /// <summary>
        /// 通过文件ID下载文件
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        // [HttpGet("download/{fileId}")]
        // public IActionResult Download([FromRoute] long fileId)
        // {
        //     var sysFile = _sysFileService.Queryable().Where(it => it.Id == fileId).First();
        //     if (sysFile == null)
        //     {
        //         throw new CustomException("服务器上不存在此文件");
        //     }
        //
        //     Stream? stream;
        //     switch ((StoreType)Enum.Parse(typeof(StoreType), sysFile.StoreType.ToString() ?? string.Empty))
        //     {
        //         case StoreType.LOCAL:
        //             Logger.Info("本地存储");
        //             stream = sysFile.IsEncrypted == "1" ? _sysFileService.DecryptSysFileStream(sysFile.FileUrl) 
        //                 : new FileStream(sysFile.FileUrl, FileMode.Open);
        //             break;
        //         case StoreType.ALIYUN:
        //             stream = AliyunOssHelper.DownloadFile(sysFile.FileUrl, "", sysFile.IsEncrypted == "1");
        //             break;
        //         default:
        //             throw new CustomException("不支持的存储类型");
        //     }
        //     if (stream != null)
        //     {
        //         return new FileStreamResult(stream, "application/octet-stream")
        //         {
        //             FileDownloadName = sysFile.RealName
        //         };
        //     }
        //
        //     return NoContent();
        // }
    }
}